package cn.nawang.ebeim.api.repository.impl;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;

import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;

import cn.nawang.ebeim.api.comm.BaseQuery;
import cn.nawang.ebeim.api.domain.HeartLog;
import cn.nawang.ebeim.api.repository.QueryBaseRepository;

/**
 * @ClassName: HeartLogRepositoryImpl
 * @Description: 心跳表复杂查询实现类
 * @author fanyb
 * @date Aug 6, 2015 10:58:18 AM
 * @version v1.0
 */
public class HeartLogRepositoryImpl extends BaseQuery {

  @Autowired
  private EntityManagerFactory entityManagerFactory;

  @Autowired
  private QueryBaseRepository queryBaseRepository;

  /**
   * 
   * @author fanyb
   * @Description: 查找半个小时之前的心跳表的最近六条记录
   * @param currTime 当前时间（时间戳）
   * @param halfHourAgo 半个小时之前（时间戳）
   * @param terminalId 终端id
   * @return List 返回半个小时之前的心跳表的最近六条记录
   * @date Aug 6, 201510:38:41 AM
   *
   * @修改人
   * @修改日期
   */
  public List findHalfHourList(long currTime, long halfHourAgo, String terminalId) {
    String sql = "select thl.* from tb_heart_log as thl where thl.terminal_id='" + terminalId + "' "
        + "and thl.act_time<=" + currTime + " and thl.act_time>=" + halfHourAgo
        + " ORDER BY act_time DESC " + "limit 6";
    List objList = null;
    EntityManager em = entityManagerFactory.createEntityManager();
    try {
      Query query = em.createNativeQuery(sql);
      objList = query.getResultList();
    } catch (Exception ex) {
      ex.printStackTrace();
    } finally {
      em.close();
    }
    return objList;
  }

  public List<String> findMacByUserId(String userId) {
    String sql = "SELECT DISTINCT obj.terminal_id as mac"
        + " FROM tb_heart_log obj where obj.act_user_id=?1";
    List objList = null;
    EntityManager em = entityManagerFactory.createEntityManager();
    try {
      Query query = em.createNativeQuery(sql);
      query.setParameter(1, userId);
      objList = query.getResultList();
    } catch (Exception ex) {
      ex.printStackTrace();
    } finally {
      em.close();
    }
    return objList;
  }

  public List<HeartLog> getListByTerminalIds(String terminalIds) {
    String sql = "SELECT *" + " from " + "(" + "SELECT * FROM tb_heart_log ORDER BY act_time DESC"
        + ")" + " as obj GROUP BY terminal_id HAVING terminal_id in (" + terminalIds + ")";
    List objList = null;
    List<HeartLog> list = new ArrayList<HeartLog>();
    EntityManager em = entityManagerFactory.createEntityManager();
    try {
      Query query = em.createNativeQuery(sql);
      objList = query.getResultList();
      for (Object object : objList) {
        Object[] obj = (Object[]) object;
        HeartLog log = new HeartLog((Integer) obj[0], (String) obj[1], (String) obj[5],
            ((BigInteger) obj[6]).longValue());
        list.add(log);
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    } finally {
      em.close();
    }
    return list;
  }



  /**
   * 
   * @author fanyb
   * @Description: 获取某个时间段的心跳状态为（level）的记录数
   * @param startTime 起始时间戳
   * @param endTime 结束时间戳
   * @param terminalId 终端编号
   * @param level 状态
   * @return int 某个时间段的心跳状态为（level）的记录数
   * @date Aug 6, 20153:13:23 PM
   *
   * @修改人
   * @修改日期
   */
  public int getHeartLogCount(long startTime, long endTime, String terminalId, String level) {
    String sql =
        "select count(thl.id) from tb_heart_log thl where thl.terminal_id='" + terminalId + "'";
    if (startTime != 0 && endTime != 0) {
      sql += " and thl.act_time<=" + endTime + " and thl.act_time>=" + startTime;
    }
    sql += " and thl.level='" + level + "' ";
    return queryBaseRepository.countAllData(sql);
  }

  /**
   * 
   * @author fanyb
   * @Description: 获取该终端某个时间段离线原因分析
   * @param startTime 起始时间戳
   * @param endTime 结束时间戳
   * @param terminalId 终端编号
   * @return List 该终端某个时间段离线原因分析
   * @date Aug 7, 20159:42:38 AM
   *
   * @修改人
   * @修改日期
   */
  public List findOfflineReason(long startTime, long endTime, String terminalId) {
    String sql =
        "select thl.msg,count(thl.id),thl.terminal_id from tb_heart_log thl where thl.terminal_id='"
            + terminalId + "'";
    if (startTime != 0 && endTime != 0) {
      sql += " and thl.act_time<=" + endTime + " and thl.act_time>=" + startTime;
    }
    sql += " and thl.level='3' GROUP BY msg";
    List objList = null;
    EntityManager em = entityManagerFactory.createEntityManager();
    try {
      Query query = em.createNativeQuery(sql);
      objList = query.getResultList();
    } catch (Exception ex) {
      ex.printStackTrace();
    } finally {
      em.close();
    }
    return objList;
  }

  /**
   * 
   * @author fanyb
   * @Description: 删除时间点之前的
   * @param actTime 时间点
   * @return boolean 删除结果
   * @date Sep 2, 20158:58:56 AM
   *
   * @修改人
   * @修改日期
   */
  public boolean deleteByActTimeAgo(long actTime) {
    String hql = "delete from HeartLog where actTime<:actTime ";
    Map<String, Object> paraMap = new HashMap<String, Object>();
    paraMap.put("actTime", actTime);
    boolean deleteFlag = execHQL(hql, paraMap);
    return deleteFlag;
  }

  /**
   * 
   * @author: huanghj
   * @Description: 获取用户终端
   * @param @param userId
   * @param @return
   * @return List
   * @date 2015年10月29日上午10:39:53
   *
   * @修改人
   * @修改日期
   */
  public List<Map<String, Object>> findTerminalByUser(String userId) {
    StringBuffer sb = new StringBuffer();
    sb.append(" select a.terminal_id  ,max(act_time) as act_time,bind_device_name ");
    sb.append(" from tb_datasource a LEFT JOIN tb_heart_log b on  (a.terminal_id=b.terminal_id  AND b.act_user_id=a.create_user_id)  ");
    sb.append(" where create_user_id="+userId+" and ds_type=0  GROUP BY a.terminal_id ;");
//    sb.append("   select a.terminal_id ,max(act_time) as act_time,bind_device_name ");
//    sb.append("   from tb_heart_log a,tb_datasource b ");
//    sb.append("   where act_user_id=" + userId + " AND a.act_user_id=b.create_user_id ");
//    sb.append("   and a.terminal_id=b.terminal_id GROUP BY terminal_id ");
    List<Map<String, Object>> objList = find(sb.toString());
    return objList;
  }


  public List find(String sql) {
    List<Map> objList = null;
    EntityManager em = entityManagerFactory.createEntityManager();
    try {
      Query query = em.createNativeQuery(sql);
      query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
      objList = query.getResultList();
    } catch (Exception ex) {
      ex.printStackTrace();
    } finally {
      em.close();
    }
    return objList;
  }


}
